package com.xjj.divideandconquer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class M0022GenerateParentheses {

    private List<String> result = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        // 评论区思路:选(或者选),剩下的)不能比(少
        Queue<Character> left = new LinkedList<>();
        Queue<Character> right = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            left.add('(');
            right.add(')');
        }
        findStr(left, right, new LinkedList<Character>());
        return result;
    }

    private void findStr(Queue<Character> left, Queue<Character> right, LinkedList<Character> tmp) {
        if (left.isEmpty() && right.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (char c : tmp) {
                sb.append(c);
            }
            result.add(sb.toString());
            return;
        }
        if (left.size() == right.size()) {
            // left最大只会等于right,去left
            tmp.add(left.poll());
            findStr(left, right, tmp);
            left.add(tmp.removeLast());
        } else if (left.size() != 0) {
            // 左右都行
            tmp.add(left.poll());
            findStr(left, right, tmp);
            left.add(tmp.removeLast());

            tmp.add(right.poll());
            findStr(left, right, tmp);
            right.add(tmp.removeLast());
        } else {
            // 只能放右
            tmp.add(right.poll());
            findStr(left, right, tmp);
            right.add(tmp.removeLast());
        }
    }
}
